home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Source Code / Libraries / VideoToolbox 94.11.17 / VideoToolboxSources / Shuffle.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-07-25  |  1.1 KB  |  37 lines  |  [TEXT/KAHL]

  1. /*
  2. Shuffle.c
  3. Like the Standard C function qsort(), Shuffle reorders the elements of
  4. an array, but Shuffle produces a randomized sequence.
  5.  
  6. HISTORY:
  7. 3/19/94    dgp    rewrote it to accept an arbitrary element size. It probably now
  8. runs ten times slower than when it only accepted shorts. If the loss of speed
  9. matters to anybody, let me know, as it would be easy to add fast special-case
  10. code for a few popular element sizes, e.g. sizeof(short).
  11. */
  12. #include "VideoToolbox.h"
  13. #include <assert.h>
  14.  
  15. void Shuffle(void *array,long elements,size_t elementSize)
  16. {
  17.     long i,j;
  18.     void *scratch;
  19.     char workArea[256],useMalloc;
  20.     
  21.     assert(sizeof(char)==1);
  22.     assert(StackSpace()>4000);
  23.     useMalloc=sizeof(workArea)<elementSize;
  24.     if(useMalloc){
  25.         scratch=malloc(elementSize);
  26.         assert(scratch!=NULL);
  27.     }else scratch=workArea;
  28.     for(i=0;i<elements;i++){
  29.         j=nrand(elements);
  30.         // swap i-th and j-th elements
  31.         memcpy(scratch,(char *)array+j*elementSize,elementSize);
  32.         memcpy((char *)array+j*elementSize,(char *)array+i*elementSize,elementSize);
  33.         memcpy((char *)array+i*elementSize,scratch,elementSize);
  34.     }
  35.     if(useMalloc)free(scratch);
  36. }
  37.